<template>
  <div class="flex flex-col">
    <div class="comps" v-loading="loading">
      <el-row :gutter="10">
        <el-col :span="6">
          <div class="comp-box comp-plain">
            <div class="comp-body" style="font-size: 16px;">
              <el-button
                class="comp-action"
                type="text"
                @click="handleShowCreate()"
              >
                <template #icon>
                  <JIcon :icon="DFT_ICONS.add" />
                </template>新模板</el-button>
              <el-button
                class="comp-action"
                type="text"
                @click="handleShowConfig()"
              >配置参考</el-button>
            </div>
          </div>
        </el-col>
        <el-col :span="6" v-for="temp in templates" :key="temp.id">
          <div
            class="comp-box comp-plain"
            :class="{ 'active': selected && temp.id === selected.id }"
            @click="handleSelect(temp)"
          >
            <div class="comp-body">
              <div v-html="temp.temp_name"></div>
              <p v-html="temp.temp_code" v-copy="temp.temp_code"></p>
            </div>
            <div class="actions">
              <el-button size="small" type="text" @click="handleDownload(temp)">下载</el-button>
              <el-button size="small" type="text" @click="handleShowEdit(temp)">编辑</el-button>
              <el-button size="small" type="text" @click="handleShowDelete(temp)">删除</el-button>
            </div>
            <JIcon :icon="DFT_ICONS.check" class="comp-selected" />
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog
      :title="formTempWinName"
      v-model="formTempWinShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <div class="form-props" v-if="formTempWinShow">
        <el-form
          :model="form"
          ref="createForm"
          class="form mp-form"
          label-width="100px"
        >
          <el-form-item
            label="模板编码"
            prop="temp_code">
            <el-input
              v-model="form.temp_code"
              autocomplete="off"
              placeholder="模板唯一编码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="模板名称"
            prop="temp_name">
            <el-input
              v-model="form.temp_name"
              autocomplete="off"
              placeholder="模板中文名"
            ></el-input>
          </el-form-item>
          <el-form-item label="模板文件" prop="thumb">
            <FilePicker
              :info="form.file"
              @change="handleFileChange"
            />
          </el-form-item>
          <el-form-item label="模板描述" prop="remark">
            <el-input
              v-model="form.temp_remark"
              type="textarea"
              :rows="2"
              autocomplete="off"
            />
          </el-form-item>
          <div style="text-align:center;">
            <el-button
              type="primary"
              @click="handleSave()"
            >确 定</el-button>
            <el-button
              @click="handleCustomCloseWin()"
            >取 消</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      title="打印模板字段配置参考"
      v-model="formConfigShow"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="1000px">
      <el-tabs v-model="configActiveTab">
        <el-tab-pane v-for="t in tabs" :label="t.label" :name="t.name">
          <el-row gutter="10">
            <el-col v-if="t.type === 'formdata'" :span="24">
              <el-tag class="render-prop" size="large">
                <b v-copy="t.label">{{t.label}}</b>
                <span @click="handleCopyProp(t, t)">{{t.name}}</span>
              </el-tag>
            </el-col>
            <el-col v-for="rp in t.items" :span="8">
              <el-tag class="render-prop" size="large">
                <span v-copy="rp.label">{{rp.label}}</span>
                <span v-if="rp.type === 'sign'" @click="handleCopyProp(rp, t, 'time')">签名时间</span>
                <span @click="handleCopyProp(rp, t)">{{rp.name}}</span>
              </el-tag>
            </el-col>
          </el-row>

          <template v-if="t.type === 'self' && t.isFlow">
            <h6 style="margin: 10px 0;font-size: 15px;">流程相关字段</h6>
            <el-row gutter="10">
              <el-col :span="24">
                <el-tag class="render-prop" size="large">
                  <b v-copy="flowTag.label">{{flowTag.label}}</b>
                  <span @click="handleCopyProp(flowTag, flowTag)">{{flowTag.name}}</span>
                </el-tag>
              </el-col>
              <el-col v-for="rp in flowTag.items" :span="8">
                <el-tag class="render-prop" size="large">
                  <span v-copy="rp.label">{{rp.label}}</span>
                  <span @click="handleCopyProp(rp, t)">{{rp.name}}</span>
                </el-tag>
              </el-col>
            </el-row>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import _ from 'lodash';
import {DFT_ICONS} from "@jzl/icons";
import {api} from "@jzl/api";
import { $utils, $jui } from '@jzl/utils'

const props = defineProps({
  formId: [String, Number]
});

const DFT = {
  temp_code: '',
  temp_name: '',
  temp_remark: '',
  file_id: null,
  form_id: null,
  file: {
    file_id: null,
    file_name: "",
    file_class: null,
    file_path: ""
  }
};

const loading = ref(false);
const templates = ref([]);
const selected = ref(null);
const formTempWinName = ref('');
const formTempWinShow = ref(false);
const form = ref(_.cloneDeep(DFT));
const formConfigShow = ref(false);
const renderProps = ref([]);
const formInfo = ref(null);
const configActiveTab = ref('');
const tabs = ref([]);
const flowTag = ref({
  type: "formdata",
  name: "_flows",
  label: '流程',
  items: [{
    type: "input",
    name: "fn_userName",
    label: "审核人"
  }, {
    type: "input",
    name: "fn_remark",
    label: "审核人意见"
  }, {
    type: "input",
    name: "fn_userDept",
    label: "审核人部门"
  }, {
    type: "sign",
    name: "fn_sign",
    label: "审核人签字"
  }, {
    type: "input",
    name: "fn_time",
    label: "审核时间"
  }, {
    type: "input",
    name: "fn_nodeName",
    label: "审核节点名"
  }, {
    type: "input",
    name: "fn_result",
    label: "审核结果"
  }]
});

const init = async () => {
  loading.value = true;

  if (!props.formId) return;

  const datas = await api.temp.getTempsByForm(props.formId);

  templates.value = datas || [];
  loading.value = false;

  const formInfo = await api.form.getFormById(props.formId);
  const selfFormCode = _.get(formInfo, 'form_code');
  const isFlow = _.get(formInfo, 'use_type') === 'WORKFLOW';

  const self = { type: 'self', isFlow, name: selfFormCode, label: '当前属性', items: [] };
  const rels = [];
  const items = _.get(formInfo, 'items');

  if (items && items.length) {
    for (let i = 0; i < items.length; i++) {
      const it = items[i];

      if (it.type === 'formrel' || it.type === 'formdata') {
        const formCode = _.get(it, 'rel_code');
        const itemName = _.get(it, 'name');
        let name = `${it.type === 'formrel' ? '父' : '子'}:${it.label}`;

        if (it.form_item_code === '_ADMIN') {
          name = '用户数据';

          if (selfFormCode === '_ADMIN') continue;
        }
        if (formCode) {
          const form = await api.form.getFormByCode(formCode);
          const formdataItems = _.filter(_.get(form, 'items'), it => {
            return it.type !== 'formdata' && it.type !== 'formrel_item';
          });
          rels.push({
            type: it.type,
            name: it.name,
            itemName: it.name,
            label: name,
            items: formdataItems
          });
        }

        if (it.type === 'formdata') continue;

        self.items.push(it);
      } else if (it.type !== 'formrel_item') {
        self.items.push(it);
      }
    }
  }

  tabs.value = _.concat([self], rels);

  configActiveTab.value = selfFormCode;
  formInfo.value = formInfo;
};

const handleShowConfig = () => {
  formConfigShow.value = true;
};

const handleShowCreate = () => {
  form.value = _.cloneDeep(DFT);
  form.value.temp_code = $utils.getNanoid(12);
  formTempWinName.value = '新增模板';
  formTempWinShow.value = true;
};

const handleShowEdit = (temp) => {
  form.value = _.cloneDeep(temp);
  const name = _.get(temp, 'temp_name');
  formTempWinShow.value = true;
  formTempWinName.value = `修改模板【${name}】`;
};

const handleShowDelete = async (func) => {
  const name = _.get(func, 'temp_name');
  const typeName = '模板';

  const msg = `确定删除${typeName}【${name}】?`;
  $jui.confirm(msg, '删除确认').then(async () => {
    const ret = await api.temp.removeTemp(func.id);
    if (!ret) return;
    init();
  }).catch(() => {
    // Handle cancel
  });
};

const handleSelect = (func) => {
  selected.value = func;
};

const handleSave = async () => {
  const formClone = _.cloneDeep(form.value);
  let tip = '';

  if (!formClone) return;

  if (!formClone.temp_name) {
    tip = '名称不能为空！';
  }

  if (tip) {
    $notify.error({
      title: '提示',
      message: tip
    });
    return;
  }

  if (!formClone.form_id) {
    formClone.form_id = props.formId;
  }

  loading.value = true;

  let ret = null;
  if (formClone.id) {
    ret = await api.temp.updateTemp(formClone);
  } else {
    ret = await api.temp.createTemp(formClone);
  }

  if (ret) {
    formTempWinShow.value = false;
    init();
  }

  loading.value = false;
};

const handleCustomCloseWin = () => {
  formTempWinShow.value = false;
};

const handleFileChange = (file) => {
  if (file) {
    form.value.file_id = file.id;
  } else {
    form.value.file_id = null;
  }

  form.value.file = file;
};

const handleDownload = (temp) => {
  const filePath = _.get(temp, 'file.file_path');
  if (filePath) {
    $utils.downloadFileStatic(filePath);
  } else {
    $jui.toast('文件不存在！');
  }
};

const handleCopyProp = (prop, cate, copyType = "value") => {
  let txt = '';

  if (cate.type === 'formdata' && prop === cate) {
    txt = `{#${cate.name}}{/${cate.name}}`;
  } else {
    let propName = "";

    if (cate.type === 'self' || cate.type === 'formdata') {
      propName = prop.name;

      if (prop.type === 'formrel') {
        propName = `${prop.name}__label`;
      }
    } else if (cate.type === 'formrel') {
      propName = `${cate.itemName}.${prop.name}`;
    }

    if (prop.type === 'image') {
      txt = `{%${propName}}`;
    } else if (prop.type === 'sign') {
      if (copyType === 'time') {
        txt = `{${propName}.signTime}`;
      } else {
        txt = `{%${propName}.signPath}`;
      }
    } else {
      txt = `{${propName}}`;
    }
  }

  $utils.copyText(txt);
};

onMounted(() => {
  init();
});

watch(() => props.formId, () => {
  init();
});
</script>

<style lang="scss" scoped>
.render-prop-table {
  td {
    padding: 5px 10px;
    font-size: 12px;
  }
  tr:hover {
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
  }
}

.render-prop {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;

  > span {
    flex: 1;
    padding: 0 5px;
    text-align: center;

    &:first-child {
      text-align: left;
    }

    &:last-child {
      text-align: right;
    }

    &:hover {
      background: #EEE;
      font-weight: bold;
    }
  }
}
</style>
